;(function ($) {

    $.fn.imageUploader = function (options) {
        return new imageUploader(this, options);
    };

    var imageUploader = function (element, options) {

        let $el = $(element);

        let id = $el.prop("id");

        if ($el.data('image-uploader-loaded')) {
            return;
        } else {
            $el.data('image-uploader-loaded', 1);
        }

        options = $.extend({
            title: '', // 标题
            readonly: false, // 只读
            images: [], // 默认加载的图片
            count: 0, // 允许上传的数量
            onChange: null, // 回调，选择图片后触发
            onRemove: null, // 回调，删除图片后触发
        }, options);


        let opr = '';

        if (!options.readonly) {
            opr = `<div class="weui-gallery__opr">
            <a href="javascript:" class="weui-gallery__del">
                <i class="weui-icon-delete weui-icon_gallery-delete" id="image-uploader-gallery-remove-${id}"></i>
            </a>
        </div>`;
        } else {
            opr = '';
        }

        let $gallery = $(`
    <div class="weui-gallery" id="image-uploader-gallery-${id}">
        <span class="weui-gallery__img" id="image-uploader-gallery-item-${id}"></span>
        ${opr}
    </div>
`);

        let images = ``;

        if (options.images) {
            options.images.forEach((image, index) => {
                images += `<li class="weui-uploader__file" style="background-image:url(${image})">`;
                if (!options.readonly) {
                    images += `<input type="hidden" name="${id}[]" value="${image}" />`;
                }
                images += `</li>`;
            });
        }

        let uploader = `<div class="weui-cell weui-cell_uploader">
    <div class="weui-cell__bd">
        <div class="weui-uploader">
            <div class="weui-uploader__hd">
                <p class="weui-uploader__title">${options.title}</p>`;

        if (!options.readonly) {
            uploader += `<div class="weui-uploader__info" id="image-uploader-counter-${id}">0/${options.count}</div>`;
        }

        uploader += `</div>
            <div class="weui-uploader__bd">
                <ul class="weui-uploader__files" id="image-uploader-images-${id}">
                    ${images}
                </ul>`;
        if (!options.readonly) {

            uploader += `<div class="weui-uploader__input-box" id="image-uploader-inputbox-${id}">`;

            if (navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == "micromessenger") {
                uploader += `<input id="image-uploader-input-${id}" class="weui-uploader__input" type="file" accept="image/*" />`;
            } else {
                uploader += `<input id="image-uploader-input-${id}" class="weui-uploader__input" type="file" accept="image/*" multiple="multiple" />`;
            }

            uploader += `</div>`;
        }

        uploader += `</div>
            </div>
        </div>
    </div>`;

        let $uploader = $(uploader);

        $el.append($gallery);
        $el.append($uploader);

        let tmpl = `<li class="weui-uploader__file" style="background-image:url(#url#)"><input type="hidden" name="${id}[]" value="#url#" /></li>`;

        let $galleryImg = $(`#image-uploader-gallery-item-${id}`),
                $galleryDel = $(`#image-uploader-gallery-remove-${id}`),
                $uploaderCounter = $(`#image-uploader-counter-${id}`),
                $uploaderInput = $(`#image-uploader-input-${id}`),
                $uploaderInputBox = $(`#image-uploader-inputbox-${id}`),
                $uploaderFiles = $(`#image-uploader-images-${id}`);

        $uploaderInput.on("change", function (e) {
            let files = e.target.files;
            for (let i = 0, len = files.length; i < len; ++i) {

                if (!/^(?:image\/jpeg|image\/jpg|image\/png)$/i.test(files[i].type)) {
                    weui.alert("请选择图片");
                    break;
                }

                let FReader = new window.FileReader();
                FReader.onload = function (FREvent) {

                    if ($uploaderFiles.children().length >= parseInt(`${options.count}`)) {

                        weui.alert(`最多上传${options.count}张图片`);

                        return false;
                    }

                    $tmpl = $(tmpl.replace(/#url#/g, FREvent.target.result));

                    $uploaderFiles.append($tmpl);
                    $uploaderCounter.text($uploaderFiles.children().length + `/${options.count}`);

                    if ($uploaderFiles.children().length >= options.count) {
                        $uploaderInputBox.hide();
                        // 清理file控件，防止被表单提交
                        $uploaderInput.replaceWith($uploaderInput = $uploaderInput.clone(true));
                    }

                    // 回调
                    if (options.onChange) {
                        if (/^data:image\/(\w+);base64,/.test(FREvent.target.result)) {
                            options.onChange($tmpl.index(), FREvent.target.result);
                        }
                    }
                };

                FReader.readAsDataURL(files[i]);
            }
        });

        $uploaderFiles.on("click", "li", function () {
            $galleryImg.attr("style", this.getAttribute("style"));
            $galleryDel.attr("UploaderFilesIndex", $(this).index());
            $gallery.fadeIn(100);
        });

        $galleryDel.on("click", function () {
            let index = $galleryDel.attr("UploaderFilesIndex");
            $uploaderFiles.children().eq(index).remove();
            $uploaderCounter.text($uploaderFiles.children().length + `/${options.count}`);
            $uploaderInputBox.show();

            if (options.onRemove) {
                options.onRemove(index);
            }
        });

        $gallery.on("click", function () {
            $gallery.fadeOut(100);
        });

        if ($uploaderFiles.children().length >= options.count) {
            $uploaderInputBox.hide();
        }

    };

})(window.jQuery);
